package com.zyk;

import com.zyk.attach.VM;
import net.bytebuddy.agent.ByteBuddyAgent;

import java.lang.instrument.Instrumentation;

public class Launcher {

    public static void main(String[] args) throws Exception {
        // for java -jar thisJar start agent
//        File agentFile = WhereIsUtils.findCurrentJarFile();
//        if (agentFile == null) {
//            System.out.println("未找到当前jar!");
//            return;
//        }
//        AttachLauncher.select(agentFile);

        // for fixed this jar to agent
//        File agentFile = new File("/Users/zhangyuekun/projects/ja/ja/ja/target/ja-1.0-jar-with-dependencies.jar");
//        System.out.println("====================================");
//        System.out.println("外部jvm进程: ");
//        List<VM.VMDescriptor> vmList = VM.getExternalVMList();
//        AttachLauncher.printVMList(vmList);
//        System.out.println("请输入要agent的进程id: ");
//        Scanner scan = new java.util.Scanner(System.in);
//        String input = scan.nextLine();
//        VM.attachVM(agentFile, input, "");

        // for debug
        Instrumentation inst = ByteBuddyAgent.install();
        launch(inst, "a", true);
    }

    public static void premain(String args, Instrumentation inst) {
        launch(inst, args, true);
    }

    public static void agentmain(String args, Instrumentation inst) {
        launch(inst, args, false);
    }


    private static void launch(Instrumentation inst, String appname, boolean mode) {
        String currentDirectory = System.getProperty("user.dir");
        System.setProperty("log.dir", currentDirectory + "/logs");
        System.setProperty("PID", VM.currentPid());
        Initializer.init(inst, appname, mode);
    }


}
